import re
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from users.models import User
from django.conf import settings
from oauth.models import oauthQQUser, OAuthSinaUser

from itsdangerous import TimedJSONWebSignatureSerializer as TJS

class QQCreateSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)

    access_token = serializers.CharField(write_only=True)

    mobile = serializers.CharField(max_length=11, min_length=11)

    username = serializers.CharField(read_only=True)

    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        # fields = ('mobile','password','sms_code','access_token','token','username','user_id')
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'token',
                  'username')  # Field name `user_id` is not valid for model `User`.
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8, 'max_length': 20}}

    def validate(self, attrs):

        if not re.match(r'1[3-9]\d{9}', attrs['mobile']):
            raise serializers.ValidationError({'message': '手机格式不正确!'})

        conn = get_redis_connection('sms_code')
        redis_sms_code = conn.get('sms_code:%s' % attrs['mobile'])
        if not redis_sms_code:
            raise serializers.ValidationError({'message': '短信验证码已失效!'})
        if attrs['sms_code'] != redis_sms_code.decode():
            raise serializers.ValidationError({'message': '验证码不正确!'})

        access_token = attrs.get('access_token')
        if not access_token:
            raise serializers.ValidationError({'message': 'opendid不存在,请确认!'})

        tjs = TJS(settings.SECRET_KEY, 300)
        openid = tjs.loads(access_token)
        attrs['openid'] = openid

        mobile = attrs['mobile']
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return attrs
        else:
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError({'message': '密码错误!'})
        attrs['user'] = user
        return attrs

    def create(self, validated_data):

        # mobile = validated_data['mobile']
        # password = validated_data['password']
        # try:
        #     user = User.objects.get(mobile=mobile)
        # except:
        #     user = User.objects.create_user(username=validated_data['mobile'],password=validated_data['password'],mobile=validated_data['mobile'])
        #     oauthQQUser.objects.create(user_id=user.id,openid=validated_data['openid'])
        #     # qq_user.save()  使用 模型类.objects.create 不需要使用 save() 方法
        # else:
        #     if not user.check_password(password):
        #         raise serializers.ValidationError({'message':'密码输入有误!'})
        #     # qq_user = oauthQQUser.objects.create(user_id=user.id,openid=validated_data['openid'])
        #     oauthQQUser.objects.create(user_id=user.id,openid=validated_data['openid'])
        #     # qq_user.save()
        # finally:
        #
        #     jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        #     jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #
        #     payload = jwt_payload_handler(user)
        #     token = jwt_encode_handler(payload)
        # validated_data['token'] = token
        # del validated_data['password']
        # del validated_data['sms_code']
        # del validated_data['access_token']
        # validated_data['user_id'] = user.id
        # validated_data['username'] = user.username
        user = validated_data.get('user')

        if not user:
            user = User.objects.create_user(username=validated_data['mobile'], password=validated_data['password'],
                                            mobile=validated_data['mobile'])

        oauthQQUser.objects.create(user_id=user.id, openid=validated_data['openid'])

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token
        return user
        # return {'token':token,'user_id':user.id,'username':user.username}    #不可以这么返回


class WeiboCreateSerializer(serializers.ModelSerializer):

    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    access_token = serializers.CharField(write_only=True)
    mobile = serializers.CharField(max_length=11, min_length=11)
    username = serializers.CharField(read_only=True)
    token = serializers.CharField(read_only=True)
    user_id = serializers.IntegerField(read_only=True)

    class Meta:
        model = User
        fields = ('id','username','token','sms_code','access_token','mobile','password','user_id')
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8, 'max_length': 20}}

    def validate(self, attrs):
        mobile = attrs['mobile']
        if not re.match(r'1[3-9]\d{9}',mobile):
            raise serializers.ValidationError({'message':'手机号格式不正确!'})
        sms_code = attrs['sms_code']
        conn = get_redis_connection('sms_code')
        redis_sms_code = conn.get('sms_code:%s'%mobile)
        if not redis_sms_code:
            raise serializers.ValidationError({'message':'验证码已过期!'})
        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError({'message':'验证码不正确!'})
        data = attrs['access_token']
        if not data:
            raise serializers.ValidationError({'message':'无效的access_token!'})
        tjs = TJS(settings.SECRET_KEY,300)
        access_token = tjs.loads(data)
        attrs['access_token'] = access_token

        try:
            user = User.objects.get(mobile=mobile)
        except:
            return attrs
        else:
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError({'message': '密码错误!'})
        attrs['user'] = user
        return attrs

    def create(self, validated_data):

        user = validated_data.get('user')
        if user is None:
            user = User.objects.create_user(username=validated_data['mobile'],mobile=validated_data['mobile'],password=validated_data['password'])
        OAuthSinaUser.objects.create(user_id=user.id,access_token=validated_data['access_token'])

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token
        user.user_id = user.id
        return user


